package com.xinyue.exceltool.logic.codeclass.javacode;

import com.xinyue.exceltool.config.ExcelToolConfig;
import com.xinyue.exceltool.logic.CodeTemplateService;
import com.xinyue.exceltool.logic.codeclass.AbstractCodeClassFactory;
import com.xinyue.exceltool.logic.codeclass.ClassUtil;
import com.xinyue.exceltool.logic.convert.CellValueTypeStrategyEnum;
import com.xinyue.exceltool.logic.model.ExcelClassData;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * 根据Excel配置，生成Java类代码
 *
 * @Author 王广帅
 * @Date 2021/5/9 11:04
 */

public class GenerateJavaClassFactory extends AbstractCodeClassFactory {
    private JavaClassInfo javaClassInfo = new JavaClassInfo();

    public GenerateJavaClassFactory(ExcelClassData excelClassData, ExcelToolConfig excelToolConfig) {
        super(excelClassData, excelToolConfig);
    }


    @Override
    public void createClass() {
        String className = ClassUtil.getClassName(excelClassData.getFileName());
        this.javaClassInfo.setClassName(className);
        //添加最上面的package路径
        this.javaClassInfo.getImportPackageList().add("package " + excelToolConfig.getJavaClassPackage() + ";");
        addImportPackage();
        addJavaFiled();
        writeFile();
    }

    /**
     * 添加Java类的包引用
     */
    private void addImportPackage() {
        excelClassData.getTitleCellDataMap().values().forEach(titleCellData -> {
            String importPackage = CellValueTypeStrategyEnum.getValueConvert(titleCellData.getFieldType()).getImpartPackage();
            if (importPackage != null) {
                this.javaClassInfo.getImportPackageList().add(importPackage);
            }
        });
    }

    private void addJavaFiled() {
        excelClassData.getTitleCellDataMap().values().forEach(titleCellData -> {
            String fieldTypeName = CellValueTypeStrategyEnum.getValueConvert(titleCellData.getFieldType()).getJavaFieldTypeName(titleCellData.getFieldType());
            JavaClassField javaClassField = new JavaClassField(fieldTypeName, titleCellData.getFieldName());
            String getterName = StringUtils.capitalize(javaClassField.getName());
            javaClassField.setGetterName(getterName);
            javaClassField.setComment(titleCellData.getComment());
            this.javaClassInfo.getClassFields().add(javaClassField);
        });
    }

    private void writeFile() {
        String path = excelToolConfig.getServerClassPath();
        String fileName = this.javaClassInfo.getClassName() + ".java";
        File targetFile = new File(path, fileName);
        CodeTemplateService.outFile("java_template.ftl", targetFile, this.javaClassInfo);
    }
}
